# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base

class BgImage(Base):

    #user fetch all the bg image list uploaded by admin (image_source_type = 1)
    @view_config(route_name='AppBgImgFetchRoute', request_method='POST')
    def AppBgImgFetchRoute(self):
        log.debug(self.request.POST)
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
        except Exception, e:
            log.error(e)
            map = {'RetCode': '145', 'message': 'key not found!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        RetCode, jsonStr = self.checkUserLogin(tel, tString, eString, tokenString, csc)

        if RetCode == '145':
            return Response(jsonStr)

        # get all bg image upload by default
        selectSQL = '''
            SELECT t1.MD5, t1.name, t1.path, t1.description as des, t1.timestamp as img_upload_time, t1.image_source_type, t1.price, t2.timestamp as relation_build_time FROM user_bgimage_info t2, bgimage t1 WHERE t1.MD5 = t2.MD5 AND t1.image_source_type = 1 AND t2.user_id = 6

        '''
        resultSelectAll = MySqlCRUD.selectImpl(selectSQL)

        #get user selected image list
        selectSQL = '''
            SELECT t1.MD5 FROM user_bgimage_info t2, bgimage t1, user_info t3 WHERE t1.MD5 = t2.MD5 AND t2.user_id = t3.ID AND t3.tel = %s

        '''
        resultSelectSelected = MySqlCRUD.selectImpl(selectSQL, tel)
        selectedImgList = [item['MD5'] for item in resultSelectSelected]

        #mark user selected bg as isSelected=1
        for item in resultSelectAll:
            itemMD5 = item['MD5']
            if itemMD5 in selectedImgList:
                item['isSelected'] = 1
            else:
                item['isSelected'] = 0
            thumb_path = os.path.join('/media/thumb', itemMD5[0: 2], itemMD5[2: 4], itemMD5 + '.jpg')
            item['thumb_path'] = thumb_path
            item['img_upload_time'] = item['img_upload_time'].strftime('%Y-%m-%d %H:%M:%S')
            item['relation_build_time'] = item['relation_build_time'].strftime('%Y-%m-%d %H:%M:%S')
        map = {'RetCode':'0', 'message':'成功', 'data':resultSelectAll}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)


    #user select background image
    @view_config(route_name='AppAddBgImgUserRoute', request_method='POST')
    def AppAddBgImgUserRoute(self):
        log.debug(self.request.POST)
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            md5 = postParams.getone('md5')
        except Exception, e:
            log.error(e)
            map = {'RetCode': '145', 'message': 'key not found!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        RetCode, jsonStr = self.checkUserLogin(tel, tString, eString, tokenString, csc)

        if RetCode == '145':
            return Response(jsonStr)

        selectSQL = "SELECT ID FROM user_info WHERE tel = %s"
        resultSelect = MySqlCRUD.selectImpl(selectSQL, tel)

        insertSQL = '''
            INSERT INTO user_bgimage_info (MD5, user_id, timestamp)
                VALUES(%s, %s, %s) ON DUPLICATE KEY UPDATE timestamp = %s
        '''
        resultImgInsert = MySqlCRUD.insertImpl(insertSQL, md5, resultSelect[0]['ID'], datetime.now(), datetime.now())
        log.debug('[SETUSERIMAGE][DONE] AFFECTED_ROW[' + str(resultImgInsert) +']')
        map = {'RetCode':'0', 'message':'成功'}
        jsonStr = json.dumps(map, ensure_ascii=False)
        log.debug(jsonStr)
        return Response(jsonStr)

    #user delete background image
    @view_config(route_name='AppDelBgImgUserRoute', request_method='POST')
    def AppDelBgImgUserRoute(self):
        log.debug(self.request.POST)
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            md5 = postParams.getone('md5')
        except Exception, e:
            log.error(e)
            map = {'RetCode': '145', 'message': 'key not found!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        RetCode, jsonStr = self.checkUserLogin(tel, tString, eString, tokenString, csc)

        if RetCode == '145':
            return Response(jsonStr)

        selectSQL = "SELECT ID FROM user_info WHERE tel = %s"
        resultSelect = MySqlCRUD.selectImpl(selectSQL, tel)
        deleteSQL = '''
            DELETE FROM user_bgimage_info WHERE MD5=%s AND user_id=%s
        '''
        resultImgDelete = MySqlCRUD.deleteImpl(deleteSQL, md5, resultSelect[0]['ID'])
        log.debug('[DELUSERIMAGE][DONE] AFFECTED_ROW[' + str(resultImgDelete) +']')
        map = {'RetCode':'0', 'message':'成功'}
        jsonStr = json.dumps(map, ensure_ascii=False)
        log.debug(jsonStr)
        return Response(jsonStr)


    #fetch image list user has selected
    @view_config(route_name='AppUserSelBgFetchRoute', request_method='POST')
    def AppUserSelBgFetchRoute(self):
        log.debug(self.request.POST)
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
        except Exception, e:
            log.error(e)
            map = {'RetCode': '145', 'message': 'key not found!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        RetCode, jsonStr = self.checkUserLogin(tel, tString, eString, tokenString, csc)

        if RetCode == '145':
            return Response(jsonStr)

        selectSQL = '''
            SELECT t1.MD5, t1.name, t1.path, t1.description as des, t1.timestamp as img_upload_time, t1.image_source_type, t1.price, t2.timestamp as relation_build_time FROM user_bgimage_info t2, bgimage t1, user_info t3 WHERE t1.MD5 = t2.MD5 AND t2.user_id = t3.ID AND t3.tel = %s

        '''
        resultSelect = MySqlCRUD.selectImpl(selectSQL, tel)
        for item in resultSelect:
            itemMD5 = item['MD5']
            thumb_path = os.path.join('/media/thumb', itemMD5[0: 2], itemMD5[2: 4], itemMD5 + '.jpg')
            item['thumb_path'] = thumb_path
            item['img_upload_time'] = item['img_upload_time'].strftime('%Y-%m-%d %H:%M:%S')
            item['relation_build_time'] = item['relation_build_time'].strftime('%Y-%m-%d %H:%M:%S')
        map = {'RetCode':'0', 'message':'成功', 'data':resultSelect}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)
